<template>
    <view class="container">
        <!-- Banner Image -->
        <image class="banner-image" :src="list.cover" mode="widthFix">
        </image>

        <!-- Activity Details Section -->
        <view class="activity-details">
            <view class="activity-title">活动详情</view>
            <view class="activity-info">
                <view class="info-item">
                    <view class="iconfont icon-touxiang"></view>
                    <text>招募人数：<text class="highlight">{{ list.recruitedNum }} / {{ list.recruitNum }}</text></text>
                </view>
                <view class="info-item">
                    <view class="iconfont icon-riqi"></view>
                    <text>活动时间：{{ list.startTimeText }} 至 {{ list.expireTimeText }}</text>
                </view>
                <view class="info-item">
                    <view class="iconfont icon-weizhi"></view>
                    <text>活动地址：{{ list.location }}</text>
                </view>
                <view class="info-item">
                    <view class="iconfont icon-bianhao"></view>
                    <text>活动编号：{{ list.id }}</text>
                </view>
                <view class="info-item">
                    <view class="iconfont icon-leimupinleifenleileibie"></view>
                    <text>活动类型：{{ list.activityClassText }}</text>
                </view>
                <view class="info-item">
                    <view class="iconfont icon-zhuangtai"></view>
                    <text>报名状态：<text :class="['status-badge', list.registerStatus === 1 ? 'status-success' : (list.registerStatus === 2 ? 'status-warning' : 'status-default')]">{{ list.registerStatusText }}</text></text>
                </view>
                <view class="info-item">
                    <view class="iconfont icon-shijian"></view>
                    <text>创建时间：{{ list.createTimeText }}</text>
                </view>
            </view>

            
            <!-- Description Rich Text -->
            <view class="desc-section">
                <view class="desc-title">活动介绍</view>
                <rich-text class="desc-rich" :nodes="list.description"></rich-text>
            </view>
        </view>

        <!-- Organizer Information -->
        <!-- <view class="organizer-info">
            <view class="organizer-header">
                <image class="organizer-logo" src="https://via.placeholder.com/80" mode="aspectFill"></image>
                <view class="organizer-details">
                    <text class="organizer-name">上海林上月文化传播有限公司</text>
                    <text class="organizer-rating">志愿者评价：★★★★★ 共3936条评论</text>
                    <text class="organizer-contact">活动联系人：杨*青 <view class="iconfont icon-dianhua"></view></text>
                </view>
            </view>
        </view> -->

        

        <!-- Bottom Button -->
        <view class="fixed-bottom-button">
            <view class="bottom-box">
                <tui-button 
                    margin="10px auto" 
                    shape="circle" 
                    :type="getButtonType()" 
                    :disabled="isButtonDisabled()"
                    @click="handleButtonClick"
                >
                    {{ getButtonText() }}
                </tui-button>
            </view>
        </view>

        <tui-dialog :buttons="buttons" :show="show" title="提示" @close="close" @click="buttonTap">
            <template v-slot:content>
                是否确定报名
            </template>
        </tui-dialog>
        <tui-toast ref="toast"></tui-toast>
    </view>
</template>

<script>
    export default {
        data() {
            return {
                currentCity: "杭州市", // Default city for demo
                id: 0,
            list: {},
                show: false,
                buttons: [{
                    text: '取消'
                },{
                    text: '确定',
                    color: '#586c94'
                }],
                countdown: '', // 用于展示的倒计时文本
                timer: null // 定时器标识
            };
        },
        onLoad: function (option) { //option为object类型，会序列化上个页面传递的参数
            this.id = option.id
        },
        methods: {
            // 获取活动详细信息
            // 获取活动详细信息
            getActivity() {
                var t = this
                t.$api.req(`/station/activity/get`,{
                    id: t.id
                },'GET',"JSON",false).then(res => {
                    t.list = res.data || {};
                    // 计算展示用字段
                    const start = t.list.startTime ? new Date(t.list.startTime) : null;
                    const end = t.list.expireTime ? new Date(t.list.expireTime) : null;
                    const create = t.list.createTime ? new Date(t.list.createTime) : null;

                    // 手动格式化时间
                    t.list.startTimeText = start ? this.formatDateTime(t.list.startTime) : '';
                    t.list.expireTimeText = end ? this.formatDateTime(t.list.expireTime) : '';
                    t.list.createTimeText = create ? this.formatDateTime(t.list.createTime) : '';

                    // 枚举映射
                    const classMap = {
                        1: '公益活动',
                        2: '婚恋相亲',
                        3: '志愿服务'
                    };
                    t.list.activityClassText = classMap[t.list.activityClass] || `类型${t.list.activityClass || ''}`;

                    const statusMap = {
                        0: '未报名',
                        1: '待审核',
                        2: '已通过',
                        3: '已拒绝'
                    };
                    t.list.registerStatusText = statusMap[t.list.registerStatus] || '未知';

                    // 在获取到活动详情后立即启动倒计时
                    this.startCountdown();
                });
            },

            startCountdown() {
                // 检查 expireTime 是否有效
                const expireTime = new Date(this.list.expireTime).getTime();
                if (isNaN(expireTime)) {
                    console.error("Invalid expireTime:",this.list.expireTime);
                    this.countdown = '';
                    return;
                }

                this.timer = setInterval(() => {
                    const now = new Date().getTime();
                    const timeRemaining = expireTime - now;

                    if (timeRemaining <= 0) {
                        clearInterval(this.timer);
                        this.countdown = '报名已截止';
                        return;
                    }

                    // 计算剩余时间
                    const days = Math.floor(timeRemaining / (1000 * 60 * 60 * 24));
                    const hours = Math.floor((timeRemaining % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
                    const minutes = Math.floor((timeRemaining % (1000 * 60 * 60)) / (1000 * 60));
                    const seconds = Math.floor((timeRemaining % (1000 * 60)) / 1000);

                    // 如果有 NaN，输出日志查看是哪部分出错
                    if (isNaN(days) || isNaN(hours) || isNaN(minutes) || isNaN(seconds)) {
                        console.error("Invalid countdown calculation:",{ timeRemaining,days,hours,minutes,seconds });
                    }

                    this.countdown = `剩余 ${days}天 ${hours}小时 ${minutes}分钟 ${seconds}秒`;

                },1000);
            },

            // 报名按钮
            apply() {
                this.show = true
            },

            close() {
                this.show = false
            },

            buttonTap(e) {
                if (e.index === 1) { // 确定按钮
                    this.submitRegistration();
                } else { // 取消按钮
                    this.close();
                }
            },

            // 提交报名申请
            submitRegistration() {
                const t = this;
                
                // 获取用户信息 - 尝试多种存储方式
                let userInfo = this.f.storage('user_data') || {};
                let token = this.$cfg.token() || '';
                
                // 如果婚恋模块的用户信息不存在，尝试使用系统用户信息
                if (!userInfo.userId) {
                    const sysUserInfo = this.$cfg.user() || {};
                    userInfo = sysUserInfo;
                }
                
                // 调试信息
                console.log('婚恋用户信息:', this.f.storage('user_data'));
                console.log('系统用户信息:', this.$cfg.user());
                console.log('当前用户信息:', userInfo);
                console.log('Token:', token);
                console.log('用户ID字段:', userInfo.userId || userInfo.id);
                
                // 检查用户ID（支持userId和id两种字段名）
                const userId = userInfo.userId || userInfo.id;
                if (!userId) {
                    uni.showToast({
                        title: '请先登录',
                        icon: 'none'
                    });
                    return;
                }

                // 显示加载中
                uni.showLoading({
                    title: '提交中...'
                });

                // 根据接口文档，只需要传递 id 作为 query 参数
                // Query 参数：id（活动编号）
                // Header 参数：tenant-id 和 Authorization（已在请求拦截器中自动添加）
                // 请求体：空对象（POST 请求需要请求体，但不需要参数）
                const requestData = {};
                
                // 调试信息
                console.log('报名请求参数:', {
                    url: `/station/activity/register?id=${t.id}`,
                    method: 'POST',
                    data: requestData
                });

                // 调用报名接口
                // id 作为 query 参数传递，不需要在请求体中
                t.$api.req(`/station/activity/register?id=${t.id}`, requestData, 'POST', 'JSON', false, {
                    'tenant-id': 1,
                    'Authorization': token
                }).then(res => {
                    uni.hideLoading();
                    
                    if (res.code === 0) {
                        uni.showToast({
                            title: '报名成功',
                            icon: 'success',
                            duration: 2000
                        });
                        
                        // 更新报名状态
                        t.list.registerStatus = 2; // 直接设为已通过
                        t.list.registerStatusText = '已通过';
                        
                        // 更新已招募人数
                        t.list.recruitedNum = (t.list.recruitedNum || 0) + 1;
                        
                        // 关闭弹窗
                        t.close();
                        
                        // 可选：刷新页面数据
                        // t.getActivity();
                    } else {
                        uni.showToast({
                            title: res.msg || '报名失败',
                            icon: 'none'
                        });
                    }
                }).catch(err => {
                    uni.hideLoading();
                    console.error('报名失败:', err);
                    uni.showToast({
                        title: '网络错误，请重试',
                        icon: 'none'
                    });
                });
            },

            // 获取按钮文本
            getButtonText() {
                if (this.list.registerStatus === 1) {
                    return '待审核';
                } else if (this.list.registerStatus === 2) {
                    return '已通过';
                } else if (this.list.registerStatus === 3) {
                    return '已拒绝';
                } else {
                    return `我要报名（${this.countdown}）`;
                }
            },

            // 获取按钮类型
            getButtonType() {
                if (this.list.registerStatus === 1) {
                    return 'warning';
                } else if (this.list.registerStatus === 2) {
                    return 'success';
                } else if (this.list.registerStatus === 3) {
                    return 'gray';
                } else {
                    return 'primary';
                }
            },

            // 判断按钮是否禁用
            isButtonDisabled() {
                return this.list.registerStatus !== 0; // 只有未报名状态才能点击
            },

            // 处理按钮点击
            handleButtonClick() {
                if (this.isButtonDisabled()) {
                    return;
                }
                this.apply();
            },

            // 手动格式化时间
            formatDateTime(timestamp) {
                const date = new Date(timestamp);
                const year = date.getFullYear();
                const month = String(date.getMonth() + 1).padStart(2, '0');
                const day = String(date.getDate()).padStart(2, '0');
                const hours = String(date.getHours()).padStart(2, '0');
                const minutes = String(date.getMinutes()).padStart(2, '0');
                const seconds = String(date.getSeconds()).padStart(2, '0');
                
                return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
            }
        },
        onShow() {
            this.getActivity();
        }
    };
</script>

<style>
    /* Container setup */
    .container {
        background-color: #f8f9fa;
        padding-bottom: 100px;
    }

    /* Banner image */
    .banner-image {
        width: 100%;
        height: 600rpx;
    }

    /* Activity Details */
    .activity-details {
        background-color: #ffffff;
        padding: 30rpx;
        border-bottom-left-radius: 24rpx;
        border-bottom-right-radius: 24rpx;
        box-shadow: 0 8rpx 16rpx rgba(0, 0, 0, 0.1);
    }

    .activity-title {
        font-size: 40rpx;
        font-weight: bold;
        color: #333333;
    margin-bottom: 20rpx;
    }

    .activity-info {
        display: flex;
        flex-direction: column;
        gap: 15rpx;
    }

    .info-item {
        display: flex;
        align-items: center;
        font-size: 28rpx;
        color: #666666;
        line-height: 1.5;
    }

    .info-item .iconfont {
        font-size: 34rpx;
        color: #48a473;
        margin-right: 10rpx;
    }

    .highlight {
        color: #48a473;
        font-weight: bold;
    }

/* 状态徽标 */
.status-badge {
    padding: 6rpx 12rpx;
    border-radius: 999rpx;
    margin-left: 8rpx;
}
.status-success {
    background: #e8f7ee;
    color: #27ae60;
}
.status-warning {
    background: #fff6e6;
    color: #fa8c16;
}
.status-default {
    background: #f0f0f0;
    color: #999;
}


    /* Description */
    .desc-section {
        margin-top: 30rpx;
        background: #fff;
        padding: 20rpx;
        border-radius: 16rpx;
    }
    .desc-title {
        font-size: 32rpx;
        font-weight: 600;
        margin-bottom: 16rpx;
        color: #333;
    }
    .desc-rich {
        font-size: 28rpx;
        color: #444;
        line-height: 1.8;
        word-break: break-all;
    }

    /* Organizer Information */
    .organizer-info {
        background-color: #ffffff;
        padding: 30rpx;
        margin-top: 30rpx;
        border-radius: 24rpx;
        box-shadow: 0 8rpx 16rpx rgba(0, 0, 0, 0.1);
    }

    .organizer-header {
        display: flex;
        align-items: center;
    }

    .organizer-logo {
        width: 100rpx;
        height: 100rpx;
        border-radius: 50%;
        margin-right: 25rpx;
    }

    .organizer-details {
        flex: 1;
    }

    .organizer-name {
        font-size: 34rpx;
        font-weight: bold;
        color: #333333;
    }

    .organizer-rating {
        font-size: 26rpx;
        color: #777777;
        margin-top: 10rpx;
    }

    .organizer-contact {
        font-size: 26rpx;
        color: #48a473;
        margin-top: 10rpx;
    }

    /* assurance-section 已移除 */

    /* Bottom fixed button */
    .fixed-bottom-button {
        display: flex;
        align-items: center;
        position: fixed;
        bottom: 0;
        width: 100vw;
        height: 80px;
        background-color: #ffffff;
        box-shadow: 0 -4rpx 20rpx rgba(0, 0, 0, 0.1);
    }

    .apply-button {
        width: 90%;
        background-color: #48a473;
        line-height: 50px;
        color: #ffffff;
        height: 50px;
        font-size: 32rpx;
        font-weight: bold;
        margin: 10px auto;
        border-radius: 30rpx;
        text-align: center;
    }

    .bottom-box {
        width: 90%;
        margin: 0 auto;
    }
</style>